<div class="w-full flex flex-col overflow-auto">
  <div class="sticky top-0 flex flex-col bg-components-panel-bg w-full border-b-[0.5px] border-black/5 z-10">
    <div class="flex justify-start items-center px-3 pt-3 pb-2">
      <emoji-avatar [avatar]="xpertAgent().avatar" editable small class="shrink-0 mr-2 overflow-hidden rounded-lg shadow-sm"
        (avatarChange)="updateAvatar($event)" />
      <div class="flex flex-col items-start">
        <input
          matInput
          class="ngm-input-inline ngm-input-sm min-w-[100px] mr-2 px-1 py-0.5 text-base field font-semibold rounded-lg border border-transparent appearance-none outline-none text-gray-900 hover:bg-gray-50 focus:border-gray-300 focus:shadow-xs focus:bg-white caret-[#295EFF]"
          [placeholder]="'PAC.Xpert.EnterTitle' | translate: {Default: 'Enter title'} "
          [ngModel]="title()"
          (ngModelChange)="onTitleChange($event)"
          (blur)="onBlur()"
        />
      </div>

      <span class="flex-1"></span>

      <div class="shrink-0 flex items-center">
        <div class="flex items-center justify-center mr-1 w-8 h-8 rounded-md cursor-pointer text-text-tertiary hover:text-base-content
          hover:bg-hover-bg"
          [matTooltip]="'PAC.Xpert.RunThisAgent' | translate: { Default: 'Run this agent' }"
          (click)="openExecution()"
        >
          <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="w-5 h-5">
            <path d="M8 18.3915V5.60846L18.2264 12L8 18.3915ZM6 3.80421V20.1957C6 20.9812 6.86395 21.46 7.53 21.0437L20.6432 12.848C21.2699 12.4563 21.2699 11.5436 20.6432 11.152L7.53 2.95621C6.86395 2.53993 6 3.01878 6 3.80421Z"></path>
          </svg>
        </div>

        <div class="flex items-center justify-center mr-1 w-8 h-8 rounded-md cursor-pointer text-text-tertiary hover:text-base-content
          hover:bg-hover-bg"
          [matTooltip]="'PAC.Xpert.ShowDiagram' | translate: { Default: 'Show diagram' }"
          #mt1="cdkMenuTriggerFor"
          [cdkMenuTriggerFor]="diagramMenu"
          [cdkMenuTriggerData]="{trigger: mt1}"
        >
          <i class="ri-links-line text-lg"></i>
        </div>

        <a [href]="helpWebsite() + '/docs/ai/'" target="_blank" class="flex items-center justify-center mr-1 w-6 h-6"
          [matTooltip]="'PAC.Xpert.HelpDocumentation' | translate: { Default: 'Help Documentation' }">
          <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="w-4 h-4 text-text-tertiary hover:text-base-content">
            <path d="M13 21V23H11V21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H9C10.1947 3 11.2671 3.52375 12 4.35418C12.7329 3.52375 13.8053 3 15 3H21C21.5523 3 22 3.44772 22 4V20C22 20.5523 21.5523 21 21 21H13ZM20 19V5H15C13.8954 5 13 5.89543 13 7V19H20ZM11 19V7C11 5.89543 10.1046 5 9 5H4V19H11Z"></path>
          </svg>
        </a>
        <div class="inline-block">
          <div class="float-menu-trigger flex items-center justify-center w-8 h-8 rounded-md cursor-pointer
            text-text-tertiary hover:text-base-content hover:bg-hover-bg"

            [cdkMenuTriggerFor]="moreMenu"
          >
            <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="w-5 h-5">
              <path d="M5 10C3.9 10 3 10.9 3 12C3 13.1 3.9 14 5 14C6.1 14 7 13.1 7 12C7 10.9 6.1 10 5 10ZM19 10C17.9 10 17 10.9 17 12C17 13.1 17.9 14 19 14C20.1 14 21 13.1 21 12C21 10.9 20.1 10 19 10ZM12 10C10.9 10 10 10.9 10 12C10 13.1 10.9 14 12 14C13.1 14 14 13.1 14 12C14 10.9 13.1 10 12 10Z"></path>
            </svg>
          </div>
        </div>

        <div class="mx-3 w-[1px] h-3.5 bg-divider-regular">
        </div>

        <div class="flex items-center justify-center w-8 h-8 rounded-md cursor-pointer
          text-text-tertiary hover:text-base-content hover:bg-hover-bg"
          (click)="closePanel()"
        >
          <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="w-5 h-5">
            <path d="M11.9997 10.5865L16.9495 5.63672L18.3637 7.05093L13.4139 12.0007L18.3637 16.9504L16.9495 18.3646L11.9997 13.4149L7.04996 18.3646L5.63574 16.9504L10.5855 12.0007L5.63574 7.05093L7.04996 5.63672L11.9997 10.5865Z"></path>
          </svg>
        </div>
      </div>
    </div>
  </div>

  <div class="px-4 pb-4 space-y-4 mt-2 w-full">
    <div class="py-2 flex flex-col">
      <input matInput
        class="ngm-input-inline ngm-input-sm self-stretch mx-1 mb-1 px-1 py-0.5 text-sm field rounded-lg border border-transparent appearance-none outline-none
          hover:bg-gray-50 focus:border-gray-300 focus:shadow-xs focus:bg-white caret-[#295EFF]"
        [ngClass]="{ 'ngm-error': nameError() }"
        [ngModel]="name()"
        (ngModelChange)="onNameChange($event)"
        (blur)="onBlur()"
        [matTooltip]="'PAC.Xpert.NameExistedOrInvalid' | translate: { Default: 'Name existed or invalid, use a-zA-Z0-9 _-' }"
        [matTooltipDisabled]="!nameError()"
        [placeholder]=" ('PAC.Xpert.NameDefaultUseKey' | translate: {Default: 'Name, default use '}) +key()"
      />
      <div class="group flex px-2 py-[5px] max-h-[60px] rounded-lg overflow-y-auto border border-transparent
        text-text-secondary hover:bg-gray-50 focus:border-gray-300 focus:shadow-xs">
        <textarea
          matInput
          class="rc-textarea w-full text-sm leading-[18px] bg-transparent appearance-none outline-none resize-none placeholder:text-gray-400 caret-[#295EFF]"
          [placeholder]=" ('PAC.Xpert.AddDescription' | translate: {Default: 'Add description'}) + '...'"
          [ngModel]="xpertAgent().description"
          (ngModelChange)="onDescChange($event)"
          (blur)="onBlur()"
        >
        </textarea>
      </div>
    </div>

    <copilot-model-select [inheritModel]="xpertCopilotModel()" [modelType]="eModelType.LLM"
      [ngModel]="copilotModel()"
      (ngModelChange)="updateCopilotModel($event)" />

    <copilot-prompt-editor class="relative shadow-md ngm-card-border-gradient self-stretch"
      [tooltip]="'PAC.Xpert.SystemPromptTooltip' | translate: {Default: 'Prompts guide AI reponses with instructions and contraints. Insert parameters like {{input}}. This prompt won\'t be visible to users.'}"
      [role]="'system'"
      [variables]="variables()"
      [(prompt)]="prompt"
      (promptChange)="onPromptChange($event)"
    />

    <div class="w-full flex justify-between items-center px-4 pt-2 pb-4 rounded-xl bg-gray-50">
      <div class="flex items-center h-6">
        <div class="uppercase text-sm font-semibold text-text-secondary mr-2">
          {{ 'PAC.Xpert.MessageHistory' | translate: {Default: 'Message History'} }}
        </div>
        <i class="ri-question-line opacity-50 hover:opacity-90"
          [matTooltip]="'PAC.Xpert.AgentMemoryTip' | translate: {Default: 'Agent short-term memory, inserting message history into the conversation'}"
          matTooltipPosition="above"
        ></i>
      </div>

      <mat-slide-toggle ngm-density="xs" [ngModel]="enableMessageHistory()" (ngModelChange)="updateEnMessageHistory($event)" />
    </div>

    <!-- @if (!enableMessageHistory()) { -->
      @for (template of promptTemplates(); track template.id; let i = $index) {
        <copilot-prompt-editor class="prompt-template relative rounded-xl self-stretch border border-solid border-gray-100"
          [fullscreen]="promptTemplateFullscreen() === template.id"
          [tooltip]="'PAC.Xpert.SystemPromptTooltip' | translate: {Default: 'Prompts guide AI reponses with instructions and contraints. Insert parameters like {{input}}. This prompt won\'t be visible to users.'}"
          [variables]="variables()"
          role="human"
          [prompt]="template.text"
          (promptChange)="updatePromptTemplate(i, $event)"
          (deleted)="removePrompt(i)"
        >
          @if (promptTemplateFullscreen() === template.id) {
            <button type="button" class="action-btn action-btn-m"
              (click)="promptTemplateFullscreen.set(null)"
            >
              <i class="ri-collapse-diagonal-line"></i>
            </button>
          } @else {
            <button type="button" class="action-btn action-btn-m"
              (click)="promptTemplateFullscreen.set(template.id)"
            >
              <i class="ri-expand-diagonal-line"></i>
            </button>
          }
        </copilot-prompt-editor>
      }

      <button type="button" class="btn disabled:btn-disabled btn-tertiary btn-medium w-full mt-2 h-8 justify-center"
        (click)="addMessage()"
      >
        <i class="ri-add-line"></i>
        <div>{{ 'PAC.Xpert.AddMessage' | translate: {Default: 'Add Message'} }}</div>
      </button>
    <!-- } -->
      
    <div class="w-full flex flex-col gap-2 p-3 bg-gray-50 rounded-xl">
      <div class="flex items-center space-x-1 shrink-0">
        <div class="flex items-center justify-center w-6 h-6">
          <i class="ri-git-commit-fill text-orange-600"></i>
        </div>
        <div class="text-sm font-semibold text-gray-800">{{'PAC.Xpert.Node' | translate: {Default: 'Node'} }}</div>
      </div>

      @if (!isPrimaryAgent()) {
        <div class="flex justify-end items-center gap-1 w-full">
          <i class="ri-shield-keyhole-fill text-base text-orange-600"></i>
          <div class="text-sm">{{'PAC.Xpert.Sensitive' | translate: {Default: 'Sensitive'} }}</div>
          <mat-slide-toggle class="flex" [ngModel]="isSensitive()" (ngModelChange)="updateSensitive($event)"
            labelPosition="before"
            ngm-density="xs"
            [matTooltip]="'PAC.Xpert.SensitiveAgentTip' | translate: {Default: 'Sensitive agents require user confirmation before execution'}"
            matTooltipPosition="above"
          />
        </div>

        <div class="flex justify-end items-center gap-1 w-full">
          <i class="ri-stop-circle-line text-base text-text-secondary"></i>
          <div class="text-sm">{{'PAC.Xpert.End' | translate: {Default: 'End'} }}</div>
          <mat-slide-toggle class="flex" [ngModel]="isEnd()" (ngModelChange)="updateEnd($event)"
            labelPosition="before"
            ngm-density="xs"
            [matTooltip]="'PAC.Xpert.EndAgentTip' | translate: {Default: 'The terminal agent, the conversation ends after agent completion'}"
            matTooltipPosition="above"
          />
        </div>
      }

      <div class="flex justify-end items-center gap-1 w-full">
        <i class="ri-volume-mute-fill text-base text-sky-700"></i>
        <div class="text-sm">{{'PAC.Xpert.DisableOutput' | translate: {Default: 'Disable Output'} }}</div>
        <mat-slide-toggle class="flex" [ngModel]="disableOutput()" (ngModelChange)="updateDisableOutput($event)"
          labelPosition="before"
          ngm-density="xs"
          [matTooltip]="'PAC.Xpert.DisableOutputTip' | translate: {Default: 'Disable returning the agent\'s output to the user'}"
          matTooltipPosition="above"
        />
      </div>
      
      <div class="flex justify-end items-center gap-1 w-full">
        <i class="ri-git-close-pull-request-fill text-base text-fuchsia-700"></i>
        <div class="text-sm">{{'PAC.Xpert.ParallelToolCalls' | translate: {Default: 'Parallel tool calls'} }}</div>
        <mat-slide-toggle class="flex" [ngModel]="parallelToolCalls()" (ngModelChange)="updateParallelToolCalls($event)"
          labelPosition="before"
          ngm-density="xs"
          [matTooltip]="'PAC.Xpert.ParallelToolCallsTip' | translate: {Default: 'Whether to enable the parallel calling capability of the tool, which works for some models like OpenAI'}"
          matTooltipPosition="above"
        />
      </div>
    </div>

    <xpert-parameters-edit [ngModel]="parameters()" (ngModelChange)="onParameters($event)" />

    <xpert-studio-panel-knowledge-section class="mt-3 rounded-xl bg-gray-50 pt-2 pb-3"
      [key]="key()"
    />

    <xpert-studio-panel-toolset-section
      class="mt-3 rounded-xl bg-gray-50 pt-2 pb-3"
      [key]="key()"
    />

    <div class="h-[0.5px] bg-divider-subtle"></div>

    <div class="flex flex-col w-full px-2">
      <div class="flex justify-between items-center">
        <div class="uppercase font-semibold text-sm">
          {{'PAC.Xpert.RetryOnFailure' | translate: {Default: 'Retry on failure'} }}
        </div>

        <mat-slide-toggle class=""
          labelPosition="before"
          ngm-density="xs"
          [ngModel]="retryEnabled()"
          (ngModelChange)="updateRetry({enabled: $event})"
        />
      </div>

      @if (retryEnabled()) {
        <div class="w-full flex justify-between items-center">
          <div class="grow text-sm">
            {{'PAC.Xpert.StopAfterAttempt' | translate: {Default: 'Stop After Attempt'} }}
            <i class="ri-information-line opacity-20 hover:opacity-100"
              [matTooltip]="'PAC.Xpert.StopAfterAttemptTip' | translate: {Default: 'How many times to try before stopping'}"
              matTooltipPosition="above"
            ></i>
          </div>

          <mat-slider class="w-[200px]" ngm-density small color="accent"
            [min]="1"
            [max]="10"
            discrete
          >
            <input matSliderThumb [value]="stopAfterAttempt()"
              (dragEnd)="updateRetry({stopAfterAttempt: $event.value})" >
          </mat-slider>
    
          <input class="shrink-0 block ml-4 pl-3 w-16 h-8 appearance-none outline-none rounded-lg bg-gray-100 text-[13px] text-gra-900" 
            [min]="1"
            [max]="10"
            [step]="1"
            type="number"
            [ngModel]="stopAfterAttempt()"
            (ngModelChange)="updateRetry({stopAfterAttempt: $event})"
          >
        </div>
      }
    </div>

    <div class="h-[0.5px] bg-divider-subtle"></div>

    <div class="flex flex-col w-full px-2">
      <div class="flex justify-between items-center">
        <div class="uppercase font-semibold text-sm">
          {{'PAC.Xpert.FallbackModel' | translate: {Default: 'Fallback Model'} }}
        </div>

        <mat-slide-toggle class=""
          labelPosition="before"
          ngm-density="xs"
          [ngModel]="fallbackEnabled()"
          (ngModelChange)="updateFallback({enabled: $event})"
          [matTooltip]="'PAC.Xpert.FallbackModelTip' | translate: {Default: 'This fallback model is used when the agent model fails'}"
          matTooltipPosition="above"
        />
      </div>

      @if (fallbackEnabled()) {
        <copilot-model-select class="w-full mt-2" hiddenLabel
          [modelType]="eModelType.LLM"
          [ngModel]="fallbackModel()"
          (ngModelChange)="updateFallback({copilotModel: $event})"
        />
      }
    </div>

    <div class="h-[0.5px] bg-divider-subtle"></div>

    <xpert-error-handling class="px-2"
      [ngModel]="errorHandling()"
      (ngModelChange)="updateErrorHandling($event)"
    />

    <div class="h-[0.5px] bg-divider-subtle"></div>

    <div class="px-2 pb-2">
      <div class="flex justify-between items-center mb-2">
        <div class="flex items-center h-6">
          <div class="font-semibold uppercase text-sm text-text-primary">
            {{ 'PAC.Xpert.OutputStructure' | translate: {Default: 'Output Structure'} }}
          </div>
        </div>

        <div class="flex items-center gap-2">
          <mat-slide-toggle ngm-density="xs" 
            [matTooltip]="'PAC.Xpert.CustomOutputStructureTip' | translate: {Default: 'Whether to customize the output structure'}"
            matTooltipPosition="above"
            [(ngModel)]="enabledOutputVars" />
        </div>
      </div>

      @if (enabledOutputVars) {
        <xpert-output-variables-edit class="" 
          [ngModel]="outputVariables()"
          (ngModelChange)="updateOutputVariables($event)"
        />
      } @else {
        <div class="py-1">
          <div class="flex leading-[18px] items-center">
            <div class="font-semibold text-text-secondary">content</div>
            <div class="ml-2 system-xs-regular text-text-tertiary">string</div>
          </div>
          <div class="mt-0.5 system-xs-regular text-text-tertiary">
            {{ 'PAC.Xpert.GenerateContent' | translate: {Default: 'Generate content'} }}
          </div>
        </div>
      }

      <xpert-variables-assigner class="block mt-4"
        [title]="'PAC.Xpert.WritetoMemory' | translate: {Default: 'Write to memory'}"
        [tooltip]="'PAC.Xpert.WritetoMemoryTooltip' | translate: {Default: 'Write output content or parameters of the agent into global memory of the digital expert'}"
        type="agent"
        [variables]="variables()"
        [parameters]="outputVariables()"
        [memories]="memories()"
        (memoriesChange)="updateMemories($event)"
      />
    </div>

  </div>
</div>

@if (loading()) {
  <ngm-spin class="absolute top-0 left-0 w-full h-full"/>
}

@if (openedExecution()) {
  <div class="absolute top-0 left-0 w-full h-full z-50 bg-black/20 dark:bg-neutral-500/50 backdrop-blur-[2px]" @ifAnimationTrigger (click)="closeExecution()">
    <xpert-studio-panel-agent-execution class="absolute top-14 left-0 bottom-0 w-full rounded-t-xl bg-components-panel-bg"
      [xpertAgent]="xpertAgent()"
      [xpert]="xpert()"
      [executionId]="executionId()"
      (click)="$event.stopPropagation()"
      (close)="closeExecution()"
      />
  </div>
}

<ng-template #moreMenu>
  <div cdkMenu class="cdk-menu__medium w-60">
    <button cdkMenuItem class="ngm-cdk-menu-item px-2 py-1 max-w-full text-left"
      (click)="openExecution()">
      <i class="ri-play-line mr-1"></i>{{ 'PAC.Xpert.RunThisAgent' | translate: { Default: 'Run this agent' } }}
    </button>
    <button cdkMenuItem class="ngm-cdk-menu-item px-2 py-1 max-w-full text-left"
      [cdkMenuTriggerFor]="executionsMenu">
      <span><i class="ri-history-line mr-1"></i>{{ 'PAC.Xpert.ExecutionsHistories' | translate: { Default: 'Executions Histories' } }}</span>
    </button>

    <div class="h-[1px] bg-divider-regular my-1"></div>
    
    <button cdkMenuItem class="ngm-cdk-menu-item px-2 py-1 max-w-full text-left"
      (click)="synchronous()">
      <i class="ri-refresh-line mr-1"></i>
      <span>{{ 'PAC.Xpert.Synchronous' | translate: { Default: 'Synchronous' } }}</span>
    </button>

    <div class="h-[1px] bg-divider-regular my-1"></div>

    <button cdkMenuItem class="danger disabled:opacity-80"
      [disabled]="isPrimaryAgent()"
      [matTooltip]="'PAC.Xpert.CanntRemovePrimaryAgent' | translate: {Default: 'Cannot remove the primary Agent'}"
      matTooltipPosition="left"
      (click)="remove()">
      {{ 'PAC.Xpert.Remove' | translate: {Default: 'Remove'} }}
    </button>
  </div>
</ng-template>

<ng-template #executionsMenu>
  <div cdkMenu class="ngm-cdk-menu p-2 w-72 overflow-auto">
    @for (execution of executions(); track execution.id) {
      <button cdkMenuItem class="ngm-cdk-menu-item shrink-0 px-2 py-1 max-w-full flex justify-between items-start text-sm"
        (click)="openExecution(execution)">
        {{execution.updatedAt | relative}}
        <span class="px-1 rounded-md border-light text-xs">{{execution.elapsedTime | number}}ms</span>
      </button>
    } @empty {
      <div class="text-text-secondary m-2">{{'PAC.Xpert.NoExecutionYet' | translate: { Default:'No execution yet'} }}</div>
    }
  </div>
</ng-template>

<ng-template #diagramMenu>
  <div cdkMenu @overlayAnimation1 class="min-w-[100px] min-h-[200px] max-w-xl max-h-[600px] p-4 relative bg-components-panel-bg-blur">
    @if (diagram$ | async; as diagram) {
      @if (diagram.image) {
        <img [src]="diagram.image" alt="Diagram Image">
      } @else {
        <div class="w-8 h-8 flex justify-center items-center mb-2 rounded-xl bg-slate-50 shadow-sm text-text-warning">
          <i class="ri-error-warning-line"></i>
        </div>
        <div class="text-sm text-text-warning">{{diagram.error}}</div>
      }
    } @else {
      <ngm-spin class="absolute top-0 left-0 w-full h-full" />
    }
    <button type="button" class="btn rounded-xl justify-center absolute top-2 right-2 w-8 h-8" (click)="refreshDiagram$.next()">
      <i class="ri-restart-line"></i>
    </button>
  </div>
</ng-template>